package com.emm.yixun.customer.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.BusinessAbnormaService;
import com.emm.yixun.basic.service.CustomerService;
import com.emm.yixun.basic.service.FamilyMemberService;
import com.emm.yixun.basic.service.HaveReceiveRefundService;
import com.emm.yixun.basic.service.ImageService;
import com.emm.yixun.basic.service.NeedReceiveRefundService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.SignedService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.basic.service.TransactionRelationService;
import com.emm.yixun.common.model.BusinessAbnorma;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BusinessAbnormaDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.FamilyMemberDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.ImageDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.PayDepositDto;
import com.emm.yixun.common.model.dto.ProceedsDto;
import com.emm.yixun.common.model.dto.SignedDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.TransactionRelationDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessFlagEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.HousingFundTypeEnum;
import com.emm.yixun.common.model.enums.ImgTypeEnum;
import com.emm.yixun.common.model.enums.MemberTypeEnum;
import com.emm.yixun.common.model.enums.NeedStatusEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.StatementTypeEnum;
import com.emm.yixun.common.utils.BeanUtil;

@Service("payDepositTransactionalService")
public class PayDepositTransactionalService {
	@Autowired
	private PayDepositService service;

	@Autowired
	private SubscribeService subscribeService;

	@Autowired
	private SignedService signedService;

	@Autowired
	private FamilyMemberService familyMemberService;

	@Autowired
	private BusinessAbnormaService businessAbnormaService;

	@Autowired
	private TransactionRelationService transactionRelationService;

	@Autowired
	private NeedReceiveRefundService needReceiveRefundService;

	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;

	@Autowired
	private ImageService imageService;

	@Autowired
	private CustomerService customerService;

	@Transactional(propagation = Propagation.REQUIRED)
	public PayDepositDto addPayDepositWithTransactional(String params, User user, PayDepositDto payDepositDto) {
		PayDepositDto mDto = new PayDepositDto();
		if (null != payDepositDto.getId()) {
			service.update(payDepositDto);
			mDto.setId(payDepositDto.getId());
			mDto = service.getPayDepositDetail(mDto);
		} else {
			mDto = service.create(payDepositDto);
		}

		if (null == mDto) {
			throw new RuntimeException("新增认筹错误");
		}
		// 保存家庭成员信息
		JSONObject paramsJson = JSON.parseObject(params);
		createFamilyMember(paramsJson, payDepositDto, user);
		/*
		 * if(true){ throw new RuntimeException("阻断"); }
		 */

		// 修改客户信息
		if (payDepositDto.getCustomerId() != null) {
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(payDepositDto.getCustomerId());
			customerDto.setPeDocumentType(paramsJson.get("peDocumentTypeName") + "");
			customerDto.setPeDocumentNumber(paramsJson.get("peDocumentNumber") + "");
			customerDto.setPeContactAddress(paramsJson.get("peContactAddress") + "");
			customerDto.setPePostcode(paramsJson.get("pePostcode") + "");
			customerDto.setCustomerName(paramsJson.get("customerName") + "");
			customerService.update(customerDto);
		}
		return mDto;
	}

	public void createFamilyMember(JSONObject paramsJson, PayDepositDto payDepositDto, User user) {
		JSONArray familyMember = paramsJson.getJSONArray("familyMember");

		if (null != payDepositDto.getId()) {
			// 修改时，需要删除原家庭信息再重新插入
			FamilyMemberDto fmDto = new FamilyMemberDto();
			fmDto.setBuyId(payDepositDto.getId());
			fmDto.setMemberType(MemberTypeEnum.DEPOSIT.getNo());
			familyMemberService.destroy(fmDto);
		}

		if (null != familyMember && familyMember.size() > 0) {
			for (int i = 0; i < familyMember.size(); i++) {
				String familyMemberStr = (String) familyMember.get(i);
				FamilyMemberDto familyMemberRow = JSONObject.parseObject(familyMemberStr, FamilyMemberDto.class);
				familyMemberRow.setCustomerId(payDepositDto.getCustomerId());
				familyMemberRow.setBuyId(payDepositDto.getId());

				// familyMemberRow.setProjectId(payDepositDto.getProjectId());
				// familyMemberRow.setProjectCode(payDepositDto.getProjectCode());
				familyMemberRow.setProjectId(payDepositDto.getProjectId());
				familyMemberRow.setProjectCode(payDepositDto.getProjectCode());
				familyMemberRow.setMemberType(MemberTypeEnum.DEPOSIT.getNo());

				familyMemberRow.setAccessCode(payDepositDto.getAccessCode());
				familyMemberRow.setUserCode(payDepositDto.getUserCode());
				familyMemberRow.setMerchantId(user.getMerchantId());
				familyMemberRow.setCreateUserId(user.getId());
				familyMemberRow.setDelFlag("0");
				familyMemberRow.setUpdateUserId(user.getId());
				familyMemberRow.setUpdateTime(new Date());
				familyMemberRow.setIsDefault("0");
				familyMemberRow.setSex("3");
				FamilyMemberDto familyMemberDto = familyMemberService.create(familyMemberRow);
				if (null == familyMemberDto) {
					throw new RuntimeException("新增认筹共同购房者错误");
				}
			}
		}
	}

	// 认购
	@Transactional(propagation = Propagation.REQUIRED)
	public SubscribeDto addSubscribeWithTransactional(String params, User user, SubscribeDto subscribeDto) {

		SubscribeDto successSubscribeDto = new SubscribeDto();
		if (null != subscribeDto.getId()) {
			subscribeService.update(subscribeDto);
			successSubscribeDto.setId(subscribeDto.getId());
			successSubscribeDto = subscribeService.getSubscribeDetail(successSubscribeDto);
		} else {
			successSubscribeDto = subscribeService.create(subscribeDto);
		}
		// 保存家庭成员信息
		JSONObject paramsJson = JSON.parseObject(params);
		JSONArray familyMember = paramsJson.getJSONArray("familyMember");
		if (null != familyMember && familyMember.size() > 0) {
			if (null != subscribeDto.getId()) {
				// 修改时，需要删除原家庭信息再重新插入
				FamilyMemberDto fmDto = new FamilyMemberDto();
				fmDto.setBuyId(subscribeDto.getId());
				fmDto.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());
				familyMemberService.destroy(fmDto);
			}

			for (int i = 0; i < familyMember.size(); i++) {
				String familyMemberStr = (String) familyMember.get(i);
				FamilyMemberDto familyMemberRow = JSONObject.parseObject(familyMemberStr, FamilyMemberDto.class);
				familyMemberRow.setCustomerId(successSubscribeDto.getCustomerId());
				familyMemberRow.setBuyId(successSubscribeDto.getId());

				familyMemberRow.setProjectId(successSubscribeDto.getProjectId());
				familyMemberRow.setProjectCode(successSubscribeDto.getProjectCode());
				familyMemberRow.setMemberType(MemberTypeEnum.SUBSCRIBE.getNo());

				familyMemberRow.setAccessCode(successSubscribeDto.getAccessCode());
				familyMemberRow.setUserCode(successSubscribeDto.getUserCode());
				familyMemberRow.setMerchantId(user.getMerchantId());
				familyMemberRow.setCreateUserId(user.getId());
				familyMemberRow.setDelFlag("0");
				familyMemberRow.setUpdateUserId(user.getId());
				familyMemberRow.setUpdateTime(new Date());
				familyMemberRow.setIsDefault("0");
				familyMemberRow.setSex("3");
				familyMemberService.create(familyMemberRow);
			}
		}
		String discountApproval = subscribeDto.getDiscountApproval();
		if (discountApproval != null && discountApproval.equals("1")) {
			// 初始化销控业务异常表
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(successSubscribeDto.getId());
			businessAbnormaDto.setBusinessType("1");
			businessAbnormaDto.setDelFlag("0");
			businessAbnormaDto.setMerchantId(user.getMerchantId());
			BusinessAbnorma bab = businessAbnormaService.selectByDto(businessAbnormaDto);
			businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			businessAbnormaDto.setAccessCode(successSubscribeDto.getAccessCode());
			businessAbnormaDto.setUserCode(successSubscribeDto.getUserCode());
			businessAbnormaDto.setCreateUserId(user.getId());
			businessAbnormaDto.setUpdateUserId(user.getId());
			businessAbnormaDto.setUpdateTime(new Date());
			if (null != bab) {
				businessAbnormaDto.setId(bab.getId());
				businessAbnormaService.update(businessAbnormaDto);
			} else {
				businessAbnormaService.create(businessAbnormaDto);
			}
		}
		// 保存经纪人
		JSONArray agents = paramsJson.getJSONArray("agents");
		if (null != agents) {
			// 清空原经纪人
			TransactionRelationDto tranDto = new TransactionRelationDto();
			tranDto.setBusinessId(successSubscribeDto.getId());
			tranDto.setProjectId(successSubscribeDto.getProjectId());
			tranDto.setProjectCode(successSubscribeDto.getProjectCode());
			tranDto.setRelationType("5"); // 认购
			tranDto.setMerchantId(user.getMerchantId());
			transactionRelationService.destroy(tranDto);
			for (int i = 0; i < agents.size(); i++) {
				String agentStr = (String) agents.get(i);
				tranDto = new TransactionRelationDto();
				tranDto = JSONObject.parseObject(agentStr, TransactionRelationDto.class);
				// 当成交类型为单独成交或推荐成交时，修改分佣比例为100%
				if ("2".equals(subscribeDto.getDealCategory()) || "1".equals(subscribeDto.getDealCategory())) {
					tranDto.setProportionCommission("100");
				}
				tranDto.setBusinessId(successSubscribeDto.getId());
				tranDto.setProjectId(successSubscribeDto.getProjectId());
				tranDto.setProjectCode(successSubscribeDto.getProjectCode());
				tranDto.setRelationType("5"); // 认购
				tranDto.setAccessCode(successSubscribeDto.getAccessCode());
				tranDto.setUserCode(successSubscribeDto.getUserCode());
				tranDto.setMerchantId(user.getMerchantId());
				tranDto.setCreateUserId(user.getId());
				tranDto.setDelFlag("0");
				transactionRelationService.create(tranDto);
			}
		}

		// 修改客户信息
		if (subscribeDto.getCustomerId() != null) {
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(subscribeDto.getCustomerId());
			customerDto.setPeDocumentType(paramsJson.get("peDocumentTypeName") + "");
			customerDto.setPeDocumentNumber(paramsJson.get("peDocumentNumber") + "");
			customerDto.setPeContactAddress(paramsJson.get("peContactAddress") + "");
			customerDto.setPePostcode(paramsJson.get("pePostcode") + "");
			customerDto.setCustomerName(paramsJson.get("customerName") + "");
			customerService.update(customerDto);
		}
		return successSubscribeDto;
	}

	// 签约
	@Transactional(propagation = Propagation.REQUIRED)
	public SignedDto addSignedWithTransactional(String params, User user, SignedDto signedDto) {

		SignedDto successSignedDto = new SignedDto();
		Signed signed = new Signed();
		if (null != signedDto.getId()) {
			signedService.update(signedDto);
			signed = signedService.selectById(signedDto.getId());
			BeanUtils.copyProperties(signed, successSignedDto);
		} else {
			successSignedDto = signedService.create(signedDto);
		}
		// 保存家庭成员信息
		JSONObject paramsJson = JSON.parseObject(params);
		JSONArray familyMember = paramsJson.getJSONArray("familyMember");
		if (null != familyMember && familyMember.size() > 0) {
			if (null != signedDto.getId()) {
				// 修改时，需要删除原家庭信息再重新插入
				FamilyMemberDto fmDto = new FamilyMemberDto();
				fmDto.setBuyId(signedDto.getId());
				fmDto.setMemberType(MemberTypeEnum.SIGNED.getNo());
				familyMemberService.destroy(fmDto);
			}
			for (int i = 0; i < familyMember.size(); i++) {
				String familyMemberStr = (String) familyMember.get(i);
				FamilyMemberDto familyMemberRow = JSONObject.parseObject(familyMemberStr, FamilyMemberDto.class);
				familyMemberRow.setCustomerId(successSignedDto.getCustomerId());
				familyMemberRow.setBuyId(successSignedDto.getId());
				familyMemberRow.setProjectId(successSignedDto.getProjectId());
				familyMemberRow.setProjectCode(successSignedDto.getProjectCode());
				familyMemberRow.setMemberType(MemberTypeEnum.SIGNED.getNo());
				familyMemberRow.setAccessCode(successSignedDto.getAccessCode());
				familyMemberRow.setUserCode(successSignedDto.getUserCode());
				familyMemberRow.setMerchantId(user.getMerchantId());
				familyMemberRow.setCreateUserId(user.getId());
				familyMemberRow.setDelFlag("0");
				familyMemberRow.setUpdateUserId(user.getId());
				familyMemberRow.setUpdateTime(new Date());
				familyMemberRow.setIsDefault("0");
				familyMemberRow.setSex("3");
				familyMemberService.create(familyMemberRow);
			}
		}
		String discountApproval = successSignedDto.getDiscountApproval();
		if (discountApproval != null && discountApproval.equals("1")) {
			// 初始化销控业务异常表
			BusinessAbnormaDto businessAbnormaDto = new BusinessAbnormaDto();
			businessAbnormaDto.setBusinessId(successSignedDto.getId());
			businessAbnormaDto.setBusinessType("2");
			businessAbnormaDto.setDelFlag("0");
			businessAbnormaDto.setMerchantId(user.getMerchantId());
			BusinessAbnorma bab = businessAbnormaService.selectByDto(businessAbnormaDto);

			businessAbnormaDto.setAuditStatus(AuditStatusEnum.TOSUBMIT.getNo());
			businessAbnormaDto.setAccessCode(successSignedDto.getAccessCode());
			businessAbnormaDto.setUserCode(successSignedDto.getUserCode());
			businessAbnormaDto.setCreateUserId(user.getId());
			businessAbnormaDto.setUpdateUserId(user.getId());
			businessAbnormaDto.setUpdateTime(new Date());
			if (null != bab) {
				businessAbnormaDto.setId(bab.getId());
				businessAbnormaService.update(businessAbnormaDto);
			} else {
				businessAbnormaService.create(businessAbnormaDto);
			}
		}

		// 保存经纪人
		JSONArray agents = paramsJson.getJSONArray("agents");
		if (null != agents) {
			// 清空原经纪人
			TransactionRelationDto tranDto = new TransactionRelationDto();
			tranDto.setBusinessId(successSignedDto.getId());
			tranDto.setProjectId(successSignedDto.getProjectId());
			tranDto.setProjectCode(successSignedDto.getProjectCode());
			tranDto.setRelationType("6"); // 签约
			tranDto.setMerchantId(user.getMerchantId());
			transactionRelationService.destroy(tranDto);
			for (int i = 0; i < agents.size(); i++) {
				String agentStr = (String) agents.get(i);
				tranDto = JSONObject.parseObject(agentStr, TransactionRelationDto.class);
				// 当成交类型为单独成交或推荐成交时，修改分佣比例为100%
				if ("2".equals(successSignedDto.getDealCategory()) || "1".equals(successSignedDto.getDealCategory())) {
					tranDto.setProportionCommission("100");
				}
				tranDto.setBusinessId(successSignedDto.getId());
				tranDto.setProjectId(successSignedDto.getProjectId());
				tranDto.setProjectCode(successSignedDto.getProjectCode());
				tranDto.setRelationType("6"); // 签约
				tranDto.setAccessCode(successSignedDto.getAccessCode());
				tranDto.setUserCode(successSignedDto.getUserCode());
				tranDto.setMerchantId(user.getMerchantId());
				tranDto.setCreateUserId(user.getId());
				tranDto.setDelFlag("0");
				transactionRelationService.create(tranDto);
			}
		}

		// 修改客户信息
		if (signedDto.getCustomerId() != null) {
			CustomerDto customerDto = new CustomerDto();
			customerDto.setId(signedDto.getCustomerId());
			customerDto.setPeDocumentType(paramsJson.get("peDocumentTypeName") + "");
			customerDto.setPeDocumentNumber(paramsJson.get("peDocumentNumber") + "");
			customerDto.setPeContactAddress(paramsJson.get("peContactAddress") + "");
			customerDto.setPePostcode(paramsJson.get("pePostcode") + "");
			customerDto.setCustomerName(paramsJson.get("customerName") + "");
			customerService.update(customerDto);
		}

		/*
		 * ym：应收记录、内部转账放到签约审核通过进行 // 保存应收款,删除状态为已删除，当审核通过后修改状态为未删除 saveNeedReceive(successSignedDto, paramsJson); //
		 * 保存已收款
		 * 
		 * NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto(); needReceiveRefundDto.setDocType("0");
		 * needReceiveRefundDto.setBusinessType("2"); needReceiveRefundDto.setRelationId(successSignedDto.getId());
		 * List<NeedReceiveRefund> responseList = needReceiveRefundService .selectListByDto(needReceiveRefundDto);
		 * 
		 * conversionHaveReceive(successSignedDto, responseList);
		 */
		saveSignedFile(successSignedDto, paramsJson.getString("fileArr"));
		return successSignedDto;
	}

	private void saveSignedFile(SignedDto signedDto, String fileArr) {
		if (null == fileArr || fileArr.equals(""))
			return;
		// 删除签约凭证
		ImageDto deleteImageDto = new ImageDto();
		deleteImageDto.setMerchantId(signedDto.getMerchantId());
		deleteImageDto.setObjectId(signedDto.getId());
		deleteImageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
		imageService.destroy(deleteImageDto);
		// 新增签约凭证
		String fileArrList[] = fileArr.split("[|]");
		for (String file : fileArrList) {
			if (StringUtils.isNotEmpty(file)) {
				ImageDto imageDto = new ImageDto();
				imageDto.setObjectId(signedDto.getId());
				imageDto.setTitle("签约合同附件");
				imageDto.setContent("签约合同附件");
				imageDto.setSmallUrl(file);
				imageDto.setImgType(ImgTypeEnum.SIGNED.getNo());
				imageDto.setMerchantId(signedDto.getMerchantId());
				imageDto.setUserCode(signedDto.getUserCode());
				imageDto.setAccessCode(signedDto.getAccessCode());
				imageDto.setRemark("签约合同附件");
				imageDto.setCreateUserId(signedDto.getCreateUserId());
				imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				ImageDto addImage = imageService.create(imageDto);
				if (null == addImage) {
					throw new RuntimeException("保存签约合同扫描件错误");
				}
			}
		}
	}

	public void conversionHaveReceive(Signed signed, List<NeedReceiveRefund> needList) {
		List<HaveReceiveRefund> convertList = new ArrayList<HaveReceiveRefund>();
		// 查询认筹已收
		// 查询认购已收
		// 绑定签约应收第一条
		if (signed.getSubscribeId() != null) {
			Subscribe subscribe = subscribeService.selectById(signed.getSubscribeId());
			// 认购转签约
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(subscribe.getId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认购
			haveReceiveRefundDto.setReceivablesType("1");
			// 正常
			haveReceiveRefundDto.setTransferStatus("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				for (HaveReceiveRefund have : haveReceiveList) {
					if (!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
						convertList.add(have);
					}
				}
			}

		} else if (signed.getPayDepositId() != null) {
			// 认筹转认购
			HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
			haveReceiveRefundDto.setRelationId(signed.getPayDepositId());
			// 已收
			haveReceiveRefundDto.setDocType("0");
			// 认筹
			haveReceiveRefundDto.setReceivablesType("0");
			List<HaveReceiveRefund> haveReceiveList = haveReceiveRefundService.selectListByDto(haveReceiveRefundDto);
			if (null != haveReceiveList && haveReceiveList.size() > 0) {
				for (HaveReceiveRefund have : haveReceiveList) {
					if (!have.getBusinessFlag().equals(BusinessFlagEnum.BUSINESSFLAG_11.getNo())) {
						convertList.add(have);
					}
				}

			}
		}

		// 查找应收
		NeedReceiveRefund tempNeedReceive = null;
		for (NeedReceiveRefund nrr : needList) {
			String housingFundTyp = nrr.getHousingFundType();
			if (housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_5.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_6.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_10.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_12.getNo())
					|| housingFundTyp.equals(HousingFundTypeEnum.FUNDTYPE_17.getNo())) {
				tempNeedReceive = nrr;
				break;
			}
		}
		if (null != tempNeedReceive && convertList.size() > 0) {
			try {
				HaveReceiveRefund haveReceiveRefund = null;
				BigDecimal totalRealAmount = BigDecimal.ZERO;
				for (HaveReceiveRefund hrr : convertList) {
					totalRealAmount = totalRealAmount.add(hrr.getRealAmount());
					if (null == haveReceiveRefund)
						haveReceiveRefund = hrr;
				}

				// 转到应收下
				HaveReceiveRefundDto haveReceiveRefundDto = new HaveReceiveRefundDto();
				haveReceiveRefundDto = BeanUtil.convert2T(haveReceiveRefundDto, haveReceiveRefund);
				haveReceiveRefundDto.setId(null);
				haveReceiveRefundDto.setRelationId(signed.getId());
				haveReceiveRefundDto.setReceivablesType("2");
				haveReceiveRefundDto.setReceivablesId(tempNeedReceive.getId());
				haveReceiveRefundDto.setHousingFundType(tempNeedReceive.getHousingFundType());
				if (signed.getSubscribeId() != null) {
					// 认购转签约
					haveReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_13.getNo());
				} else if (signed.getPayDepositId() != null) {
					// 认筹转签约
					haveReceiveRefundDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_12.getNo());
				}
				haveReceiveRefundDto.setTransferStatus("0");
				haveReceiveRefundDto.setBillCode("");
				haveReceiveRefundDto.setRealAmount(totalRealAmount);
				haveReceiveRefundDto.setStatementId(null);
				haveReceiveRefundDto.setStatementType(Long.valueOf(StatementTypeEnum.TRANSFER.getNo()));
				haveReceiveRefundDto.setStatementDate(new Date());
				haveReceiveRefundDto.setRemark("系统内部转账");
				haveReceiveRefundDto.setCreateTime(new Date());
				haveReceiveRefundService.create(haveReceiveRefundDto);

				for (HaveReceiveRefund hrr : convertList) {
					// 原记录更新为转出
					HaveReceiveRefundDto updateDto = new HaveReceiveRefundDto();
					updateDto.setId(hrr.getId());
					updateDto.setTransferStatus("1");
					haveReceiveRefundService.update(updateDto);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	public void saveNeedReceive(SignedDto signed, JSONObject paramsJson) {
		JSONArray needReceive = paramsJson.getJSONArray("needReceive");
		if (null != needReceive && needReceive.size() > 0) {
			for (int i = 0; i < needReceive.size(); i++) {
				String needReceiveStr = (String) needReceive.get(i);
				NeedReceiveRefundDto needReceiveRefundDto = JSONObject.parseObject(needReceiveStr,
						NeedReceiveRefundDto.class);
				needReceiveRefundDto.setRelationId(signed.getId());
				needReceiveRefundDto.setBusinessType("2");
				needReceiveRefundDto.setCustomerId(signed.getCustomerId());
				needReceiveRefundDto.setRoomId(signed.getRoomId());
				needReceiveRefundDto.setStatus("1");
				needReceiveRefundDto.setPostponedStatus("0");
				needReceiveRefundDto.setDocType("0");
				needReceiveRefundDto.setRemark("签约收款");
				needReceiveRefundDto.setMerchantId(signed.getMerchantId());
				needReceiveRefundDto.setPaymentMethod(signed.getPaymentMethod());
				needReceiveRefundDto.setUserCode(signed.getUserCode());
				needReceiveRefundDto.setAccessCode(signed.getAccessCode());
				needReceiveRefundDto.setCreateUserId(signed.getCreateUserId());
				needReceiveRefundDto.setDelFlag("0");
				needReceiveRefundDto.setUpdateUserId(signed.getUpdateUserId());
				needReceiveRefundDto.setUpdateTime(new Date());
				NeedReceiveRefundDto nrrdSaveResponse = needReceiveRefundService.create(needReceiveRefundDto);
				if (null == nrrdSaveResponse) {
					throw new RuntimeException("保存签约应收信息错误");
				}
			}
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void haveReceiveOperationWithTransactional(ProceedsDto proceedsDto, NeedReceiveRefund needReceiveRefund,
			boolean enoughFlag, HaveReceiveRefundDto hrrdDto) {
		HaveReceiveRefundDto haveReceiveRefundDto = haveReceiveRefundService.create(hrrdDto);

		if (StatementTypeEnum.POS_TRANSFER.getNo().equals(proceedsDto.getStatementType())) {
			if (StringUtils.isNotEmpty(proceedsDto.getServiceFee())) {
				// 手续费
				HaveReceiveRefundDto haveReceiveRefundFeeDto = new HaveReceiveRefundDto();
				BeanUtils.copyProperties(haveReceiveRefundDto, haveReceiveRefundFeeDto);
				haveReceiveRefundFeeDto.setRealAmount(new BigDecimal(proceedsDto.getServiceFee()));
				haveReceiveRefundFeeDto.setStatementType(Long.parseLong(StatementTypeEnum.POS_TRANSFER.getNo()));
				// 手续费皆为一次性支付
				haveReceiveRefundFeeDto.setPaymentMethod(PaymentMethodEnum.LUMP_SUM.getNo());
				// 手续费无经纪人、机构
				haveReceiveRefundFeeDto.setAgentName(null);
				haveReceiveRefundFeeDto.setOrgName(null);
				// 手续费营收日期定为当天
				haveReceiveRefundFeeDto.setReceivablesDate(Calendar.getInstance().getTime());
				// 房款类型: POS手续费
				haveReceiveRefundFeeDto.setHousingFundType(HousingFundTypeEnum.FUNDTYPE_8.getNo());
				// 业务标志: POS手续费
				haveReceiveRefundFeeDto.setBusinessFlag(BusinessFlagEnum.BUSINESSFLAG_11.getNo());

				haveReceiveRefundService.create(haveReceiveRefundFeeDto);
			}
		}

		// 变更应收款记录
		// 收款金额与剩余收款总额一致,变更待收款记录为已结清
		if (enoughFlag) {
			NeedReceiveRefundDto needReceiveRefundDto = new NeedReceiveRefundDto();
			needReceiveRefundDto.setId(needReceiveRefund.getId());
			needReceiveRefundDto.setStatus(NeedStatusEnum.YES.getNo());
			needReceiveRefundService.update(needReceiveRefundDto);
		}
		// 存储收款凭证
		long haveReceiveRefundId = haveReceiveRefundDto.getId();
		String imgType = "";
		String remark = "";
		String fileArr = proceedsDto.getFileArr();
		if (BusinessTypeEnum.DEPOSIT.getNo().equals(proceedsDto.getBusinessType())) {
			imgType = ImgTypeEnum.REC_DEPOSIT.getNo();
			remark = "认筹凭证";
		} else if (BusinessTypeEnum.SUBSCRIBE.getNo().equals(proceedsDto.getBusinessType())) {
			imgType = ImgTypeEnum.REC_SUBSCRIBE.getNo();
			remark = "认购凭证";
		} else if (BusinessTypeEnum.SIGNED.getNo().equals(proceedsDto.getBusinessType())) {
			imgType = ImgTypeEnum.REC_SIGNED.getNo();
			remark = "签约凭证";
		} else if (BusinessTypeEnum.AREA.getNo().equals(proceedsDto.getBusinessType())) {
			imgType = ImgTypeEnum.REC_AREA.getNo();
			remark = "面积补差凭证";
		}
		if (StringUtils.isNotEmpty(fileArr)) {
			String fileArrList[] = fileArr.split("[|]");
			for (String file : fileArrList) {
				if (StringUtils.isNotEmpty(file)) {
					ImageDto imageDto = new ImageDto();
					imageDto.setObjectId(haveReceiveRefundId);
					imageDto.setTitle("收款凭证");
					imageDto.setContent("收款凭证");
					imageDto.setSmallUrl(file);
					imageDto.setImgType(imgType);
					imageDto.setMerchantId(haveReceiveRefundDto.getMerchantId());
					imageDto.setUserCode(haveReceiveRefundDto.getUserCode());
					imageDto.setAccessCode(haveReceiveRefundDto.getAccessCode());
					imageDto.setRemark(remark);
					imageDto.setCreateUserId(haveReceiveRefundDto.getCreateUserId());
					imageDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
					imageService.create(imageDto);
				}
			}
		}

	}
}
